package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.*;
import java.util.*;

/**
 * @author Felix
 * @date 2023/4/19
 * 事实数据动态分流处理类
 */
public class BaseDbTableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {

    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
    private Map<String,TableProcess> configMap = new HashMap<>();

    public BaseDbTableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    //预加载配置信息到自己维护的map集合中
    @Override
    public void open(Configuration parameters) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall1031_config?" +
            "user=root&password=123456&useUnicode=true&characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        String sql = "select * from gmall1031_config.table_process where sink_type = 'dwd'";
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        while (rs.next()){
            //定义一个json对象，用于封装查询出来的每一条记录
            JSONObject jsonObj = new JSONObject();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object columnValue = rs.getObject(i);
                jsonObj.put(columnName,columnValue);
            }
            //将json对象转换为实体类对象
            TableProcess tableProcess = jsonObj.toJavaObject(TableProcess.class);
            String sourceTable = tableProcess.getSourceTable();
            String sourceType = tableProcess.getSourceType();
            String key = sourceTable + ":" + sourceType;
            configMap.put(key,tableProcess);
        }
        rs.close();
        ps.close();
        conn.close();
    }

    //处理主流业务数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        // {"database":"gmall1031","xid":3692,"data":{"tm_name":"Redmi1","create_time":"2021-12-14 00:00:00","id":1},"old":{"tm_name":"Redmi"},"commit":true,"type":"update","table":"base_trademark","ts":1681439698}
        //获取操作的业务数据库表表名
        String tableName = jsonObj.getString("table");
        //获取操作的业务数据库表操作类型
        String type = jsonObj.getString("type");
        //拼接key
        String key = tableName + ":" + type;
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //根据key到广播状态中获取对应的配置信息
        TableProcess tableProcess = null;


        if((tableProcess = broadcastState.get(key)) != null
        ||(tableProcess = configMap.get(key)) != null){
            //如果配置对象不为空，说明当前数据是需要动态分流处理的事实数据
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

            //在向下游传递数据前，过滤不需要传递的属性
            String sinkColumns = tableProcess.getSinkColumns();
            filterColumn(dataJsonObj,sinkColumns);
            //在向下游传递数据前，补充输出的目的地
            String sinkTable = tableProcess.getSinkTable();
            dataJsonObj.put("sink_table",sinkTable);
            //在向下游传递数据前，补充事件时间
            Long ts = jsonObj.getLong("ts");
            dataJsonObj.put("ts", ts);
            //将其传递到下游
            out.collect(dataJsonObj);
        }

    }

    //过滤掉不需要传递的属性
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry->!fieldList.contains(entry.getKey()));
    }

    //处理广播流配置数据
    //"op":"r": {"before":null,"after":{"source_table":"activity_rule","source_type":"ALL","sink_table":"dim_activity_rule","sink_type":"dim","sink_columns":"id,activity_id,activity_type,condition_amount,condition_num,benefit_amount,benefit_discount,benefit_level","sink_pk":"id","sink_extend":null},"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1681285918409,"snapshot":"false","db":"gmall1031_config","sequence":null,"table":"table_process","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1681285918409,"transaction":null}
    //"op":"c"：{"before":null,"after":{"source_table":"aa","source_type":"ALL","sink_table":"dim_aa","sink_type":"dim","sink_columns":"a,bc,c","sink_pk":"a","sink_extend":null},"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1681286000000,"snapshot":"false","db":"gmall1031_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11302896,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1681285999620,"transaction":null}
    //"op":"u"：{"before":{"source_table":"aa","source_type":"ALL","sink_table":"dim_aa","sink_type":"dim","sink_columns":"a,bc,c","sink_pk":"a","sink_extend":null},"after":{"source_table":"aa","source_type":"ALL","sink_table":"dim_aa","sink_type":"dim","sink_columns":"a,bc,c,d","sink_pk":"a","sink_extend":null},"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1681286086000,"snapshot":"false","db":"gmall1031_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11303262,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1681286085644,"transaction":null}
    //"op":"d"：{"before":{"source_table":"aa","source_type":"ALL","sink_table":"dim_aa","sink_type":"dim","sink_columns":"a,bc,c,d","sink_pk":"a","sink_extend":null},"after":null,"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1681286126000,"snapshot":"false","db":"gmall1031_config","sequence":null,"table":"table_process","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11303656,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1681286125806,"transaction":null}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        //为了操作方便，将jsonstr转换为jsonObj
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        //获取操作类型
        String op = jsonObj.getString("op");
        //获取广播状态
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        if("d".equals(op)){
            //删除操作  将配置信息从广播状态中删除掉
            TableProcess before = jsonObj.getObject("before", TableProcess.class);
            String sinkType = before.getSinkType();
            if("dwd".equals(sinkType)){
                String sourceTable = before.getSourceTable();
                String sourceType = before.getSourceType();
                String key = sourceTable + ":" + sourceType;
                broadcastState.remove(key);
                configMap.remove(key);
            }
        }else{
            //删除外的其它操作   将配置信息封装为kv放到广播状态中
            TableProcess after = jsonObj.getObject("after", TableProcess.class);
            String sinkType = after.getSinkType();
            if("dwd".equals(sinkType)){
                String sourceTable = after.getSourceTable();
                String sourceType = after.getSourceType();
                String key = sourceTable + ":" + sourceType;
                broadcastState.put(key,after);
                configMap.put(key,after);
            }
        }
    }
}
